package com.cskaoyan.order.controller;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.commons.result.TokenInfo;
import com.cskaoyan.order.form.CreateOrderRequest;
import com.cskaoyan.order.service.OrderCoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

/**
 * @author Shuuka
 * @email 1712430536@qq.com
 * @date 2023/1/10 12:59
 */
@RestController
@RequestMapping("shopping")
@Slf4j
public class OrderCoreController {

    @Autowired
    OrderCoreService orderCoreService;


    @PostMapping("/order")
    public ResponseData<Object> order(@RequestBody @Validated CreateOrderRequest request, @RequestHeader String user_info){
        TokenInfo tokenInfo = JSON.parseObject(user_info, TokenInfo.class);
        Long uid = tokenInfo.getUid();
        String username = tokenInfo.getUsername();
        //1.参数校验
        if(uid==null){
            throw new ValidateException(
                    SysRetCodeConstants.REQUEST_DATA_ERROR.getCode(),
                    SysRetCodeConstants.REQUEST_DATA_ERROR.getMessage()
            );
        }
        //2.设置userId
        request.setUserId(uid);
        //3.设置uniqueKey,?
        request.setUniqueKey(UUID.randomUUID().toString());
        //4.调用新增订单服务
        String order = orderCoreService.createOrder(request);
        ResponseUtil<Object> stringResponseUtil = new ResponseUtil<>();
        if(order==null){
            return stringResponseUtil.setErrorMsg(
                    Integer.parseInt(SysRetCodeConstants.SYSTEM_ERROR.getCode()),
                    SysRetCodeConstants.SYSTEM_ERROR.getMessage()
            );
        }
        ResponseData<Object> objectResponseData = stringResponseUtil.setData(order, null);
        objectResponseData.setTimestamp(System.currentTimeMillis());
        return objectResponseData;
    }


}
